Valid Number

Validate if a given string is numeric.

Some examples:

"0" => true

" 0.1 " => true

"abc" => false

"1 a" => false

"2e10" => true

Note:

It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

Solution:

  1. public class Solution {
  2. public boolean isNumber(String s) {
  3. if (s == null) return false;
  4. s = s.trim();
  5. int n = s.length();
  6. if (n == 0) return false;
  7. // Define flags
  8. int signCount = 0;
  9. boolean hasE = false;
  10. boolean hasNum = false;
  11. boolean hasPoint = false;
  12. // Go through the characters
  13. for (int i = 0; i < n; i++) {
  14. char c = s.charAt(i);
  15. // invalid character
  16. if (!isValid(c)) return false;
  17. // digit
  18. if (c >= '0' && c <= '9') hasNum = true;
  19. // e or E
  20. if (c == 'e' || c == 'E') {
  21. // e 之前一定要有数字
  22. if (hasE || !hasNum) return false;
  23. // e 不能作为最后一个
  24. if (i == n - 1) return false;
  25. hasE = true;
  26. }
  27. // decimal place
  28. if (c == '.') {
  29. // 小数点不能出现在 e 之后
  30. if (hasPoint || hasE) return false;
  31. // 小数点如果在最后一位出现,那么前面必须有要数字
  32. if (i == n - 1 && !hasNum) return false;
  33. hasPoint = true;
  34. }
  35. // signs
  36. if (c == '+' || c == '-') {
  37. // 不允许超过两个符号出现
  38. if (signCount == 2) return false;
  39. // 不允许符号在最后出现
  40. if (i == n - 1) return false;
  41. // 符号出现在中间的前提是前面有 e
  42. if (i > 0 && !hasE) return false;
  43. signCount++;
  44. }
  45. }
  46. return true;
  47. }
  48. boolean isValid(char c) {
  49. return c == '.' || c == '+' || c == '-' || c == 'e' || c == 'E' || c >= '0' && c <= '9';
  50. }
  51. }